//
//  FeatureDetailViewController.m
//  UGoods
//
//  Created by dllo on 16/1/20.
//  Copyright © 2016年 蓝鸥科技.李贺. All rights reserved.
//

#import "FeatureDetailViewController.h"
#import "BaseTableView.h"
#import "FindModel.h"
#import "LHAFNetworkTool.h"
#import "BaseView.h"
#import "BaseLabel.h"
#import <MBProgressHUD.h>
#import <UIImageView+WebCache.h>
#import "PrefaceTableViewCell.h"
#import "ContentTableViewCell.h"
#import "SubtitleTableViewCell.h"
#import "ThumbnailTableViewCell.h"
#import "BaseCollectionViewFlowLayout.h"
#import "BaseCollectionView.h"
#import "FeatureCollectionViewCell.h"
#import "BuyDetailViewController.h"
#import "ConstantsDefine.h"
@interface FeatureDetailViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, retain) BaseTableView *tableView;
@property (nonatomic, retain) NSMutableArray *dataArray;
@property (nonatomic, retain) NSMutableArray *thumbnailArray;
@property (nonatomic, retain) NSMutableArray *recommendArray;
@property (nonatomic, retain) BaseCollectionView *collectionView;
@property (nonatomic, retain) MBProgressHUD *HUD;

@end

@implementation FeatureDetailViewController

- (void)dealloc
{
    [_tableView release];
    [_dataArray release];
    [_model release];
    [super dealloc];
}

- (void)handleData {
    
    NSString *str = [NSString stringWithFormat:@"http://api.ujipin.com/v4/feature/%@?format=json&channel=appstore&idfa=1EF25F55-6367-4567-B0D5-82DF4F1557CD&user_id=470825&plantform=iphone&version=314", _model.feature_id];
    self.thumbnailArray = [NSMutableArray array];
    [LHAFNetworkTool getUrl:str body:nil response:LHJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id resposeObject) {
        NSArray *array = resposeObject[@"data"][@"detail"];
        NSArray *array2 = resposeObject[@"data"][@"recommend"];
        self.dataArray = [FindModel modelHandleWithArray:array];
        self.thumbnailArray = [NSMutableArray arrayWithArray:array];
        self.recommendArray = [FindModel modelHandleWithArray:array2];
        
/************************** tableHeaderView 头部 ***************************/
        BaseView *backView = [[BaseView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200 * HEIGHT)];
        self.tableView.tableHeaderView = backView;
        [backView release];
        
        UIImageView *backImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50 * WIDTH, 50 * HEIGHT)];
        backImageView.image = [UIImage imageNamed:@"iconfont-liubianxing"];
        backImageView.center = CGPointMake(self.view.center.x, 80 * HEIGHT);
        [backView addSubview:backImageView];
        [backImageView release];
        
        BaseLabel *backLabel = [[BaseLabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 20 * HEIGHT)];
        backLabel.center = CGPointMake(self.view.center.x, 80 * HEIGHT);
        backLabel.text = @"If I could make days last forever";
        backLabel.textAlignment = NSTextAlignmentCenter;
        backLabel.font = [UIFont fontWithName:@"Zapfino" size:15 * WIDTH];
        [backView addSubview:backLabel];
        [backLabel release];
        
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(10 * WIDTH, 150 * HEIGHT, self.view.frame.size.width - 20 * WIDTH, 1)];
        lineView.backgroundColor = [UIColor grayColor];
        [backView addSubview:lineView];
        [lineView release];
        
        NSDictionary *dic = resposeObject[@"data"];
        CGRect rect = [dic[@"subtitle"] boundingRectWithSize:CGSizeMake(1000 * WIDTH, 20 * HEIGHT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:15 * WIDTH]} context:nil];
        BaseLabel *titleLabel = [[BaseLabel alloc] initWithFrame:CGRectMake(0, 0, rect.size.width + 10 * WIDTH, 20 * HEIGHT)];
        titleLabel.center = CGPointMake(self.view.center.x, 150 * HEIGHT);
        titleLabel.text = dic[@"subtitle"];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.font = [UIFont systemFontOfSize:15 * WIDTH];
        titleLabel.backgroundColor = [UIColor whiteColor];
        [backView addSubview:titleLabel];
        [titleLabel release];
        
/************************** tableFooterView 底部 ***************************/
        
        [self createCollectionView];
        
        self.navigationItem.title = dic[@"subtitle"];
        
        [self.tableView reloadData];
        [self.HUD hide:YES];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"解析失败：%@", error);
    }];
    
}

// 加载视图
- (void)handleHUD {
    // 1. 创建对象
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    // 2. 添加到当前视图中
    [self.view addSubview:self.HUD];
    // 如果设置此属性, 则置后当前的View
    self.HUD.dimBackground = NO;
    // 设置模式
    self.HUD.mode = MBProgressHUDModeIndeterminate;
    self.HUD.color = [UIColor colorWithWhite:0.800 alpha:1.000];
    [self.HUD show:YES];
}

#pragma mark tableView底部的CollectionView 

- (void)createCollectionView {
    NSLog(@"%ld", _recommendArray.count);
    BaseView *backView = [[BaseView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 260 * HEIGHT * (_recommendArray.count / 2) + 80 * HEIGHT)];
//    backView.backgroundColor = [UIColor yellowColor];
    self.tableView.tableFooterView = backView;
    [backView release];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(10 * WIDTH, 40 * HEIGHT, self.view.frame.size.width - 20 * WIDTH, 1)];
    lineView.backgroundColor = [UIColor grayColor];
    [backView addSubview:lineView];
    [lineView release];
    
    BaseLabel *titleLabel = [[BaseLabel alloc] initWithFrame:CGRectMake(0, 0, 90 * WIDTH, 20 * HEIGHT)];
    titleLabel.center = CGPointMake(self.view.center.x, 40 * HEIGHT);
    titleLabel.text = @"相关商品";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = [UIFont boldSystemFontOfSize:17];
    titleLabel.backgroundColor = [UIColor whiteColor];
    [backView addSubview:titleLabel];
    [titleLabel release];
    
    BaseCollectionViewFlowLayout *layout = [[BaseCollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((self.view.frame.size.width - 30 * WIDTH) / 2, 250 * HEIGHT);
    layout.minimumInteritemSpacing = 10 * WIDTH;
    layout.minimumLineSpacing = 10 * HEIGHT;
    layout.sectionInset = UIEdgeInsetsMake(0, 10 * WIDTH, 10 * HEIGHT, 10 * WIDTH);
    
    self.collectionView = [[BaseCollectionView alloc] initWithFrame:CGRectMake(0, 80 * HEIGHT, self.view.frame.size.width, backView.frame.size.height ) collectionViewLayout:layout];
//    _collectionView.backgroundColor = [UIColor redColor];
    _collectionView.scrollEnabled = NO;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [backView addSubview: _collectionView];
    [_collectionView release];
    [_collectionView registerClass:[FeatureCollectionViewCell class] forCellWithReuseIdentifier:@"footer"];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _recommendArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    FeatureCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"footer" forIndexPath:indexPath];
    FindModel *model = _recommendArray[indexPath.item];
    cell.model = model;
    cell.layer.borderWidth = 1;
    cell.layer.borderColor = [UIColor colorWithWhite:0.902 alpha:1.000].CGColor;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%@", indexPath);
    
    BuyDetailViewController *buy = [[BuyDetailViewController alloc] init];
    FindModel *model = _recommendArray[indexPath.item];
    buy.model = model;
    [self.navigationController pushViewController:buy animated:YES];
}

- (void)createTableView {
    self.tableView = [[BaseTableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView release];
    [_tableView registerClass:[PrefaceTableViewCell class] forCellReuseIdentifier:@"cell1"];
    [_tableView registerClass:[ContentTableViewCell class] forCellReuseIdentifier:@"cell2"];
    [_tableView registerClass:[SubtitleTableViewCell class] forCellReuseIdentifier:@"cell3"];
    [_tableView registerClass:[ThumbnailTableViewCell class] forCellReuseIdentifier:@"cell4"];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    FindModel *model = self.dataArray[indexPath.row];
     NSDictionary *dic = self.thumbnailArray[indexPath.row];
    if ([model.type_id isEqualToNumber:@1]) {
        
        PrefaceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
        cell.model = model;
        return cell;
        
    } else if ([model.type_id isEqualToNumber:@3]) {
        
        ContentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
        cell.model = model;
        return cell;
        
    } else if ([model.type_id isEqualToNumber:@5]) {
       
        SubtitleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell3"];
        cell.model = model;
        return cell;
        
    } else if ([model.type_id isEqualToNumber:@2]) {
       
        ThumbnailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell4"];
        cell.width = [dic[@"content"][@"width"] floatValue];
        cell.height = [dic[@"content"][@"height"] floatValue];
        NSString *str = dic[@"content"][@"thumbnail"];
        [cell.thumbnailImageView sd_setImageWithURL:[NSURL URLWithString:str] placeholderImage:[UIImage imageNamed:@"place3"]];
        
        return cell;
        
    } else {
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        }
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    FindModel *model = _dataArray[indexPath.row];
     NSDictionary *dic = self.thumbnailArray[indexPath.row];
    if ([model.type_id isEqualToNumber:@1]) {
        
        CGFloat h = [PrefaceTableViewCell heightWithText:model.content];
        return h + 20 * HEIGHT;
        
    } else if ([model.type_id isEqualToNumber:@3]) {
        
        CGFloat h = [ContentTableViewCell heightWithText:model.content];
        return h + 20 * HEIGHT;
        
    } else if ([model.type_id isEqualToNumber:@5]) {
        
        return 40 * HEIGHT;
        
    } else if ([model.type_id isEqualToNumber:@2]) {
        
        CGFloat width = [dic[@"content"][@"width"] floatValue];
        CGFloat height = [dic[@"content"][@"height"] floatValue];
        CGFloat h = [ThumbnailTableViewCell heigthWithImageWidth:width height:height];
        return h * HEIGHT + 20 * HEIGHT;
        
    } else {
        
        return 50 * HEIGHT;
        
    }
}

- (void)setModel:(FindModel *)model {
    if (_model != model) {
        [_model release];
        _model = [model retain];
    }
    [self handleData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self createTableView];
    [self handleHUD];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
